<?php

/**
 * Booking Controller for RoomBooking Component
 * 
 * @version 1.0
 * @package    Joomla
 * @subpackage RoomBooking
 * @copyright (C) 2011 Giovanni Marzulli
 * @license		GNU/GPL
 */
// No direct access
defined('_JEXEC') or die('Restricted access');

jimport('joomla.mail.helper');

class RoomBookingControllerBooking extends RoomBookingController {

    /**
     * constructor (registers additional tasks to methods)
     * @return void
     */
    function __construct() {
        parent::__construct();

        // Register Extra tasks
        $this->registerTask('add', 'edit');
    }

    /**
     * Method to display the view
     *
     * @access    public
     */
    function display() {
        JRequest::setVar('view', 'booking');
        $modelRoom = & $this->getModel('room');
        $modelBuilding = & $this->getModel('building');
        $view = $this->getView('booking', 'html');
        $view->setModel($modelRoom);
        $view->setModel($modelBuilding);
        parent::display();
    }

    /**
     * display the edit form
     * @return void
     */
    function edit() {
        JRequest::setVar('layout', 'form');

        $this->display();
    }

    /**
     * 
     */
    function save() {

        $repeat = JRequest::getVar('repeat_type');
        if ($repeat == "0")
            $series = $this->store();
        $i = 0;
        if ($repeat != "0" && isset($series)) {
            JRequest::setVar('series', $series);
            JRequest::setVar('id', $series);
            $this->store();
            JRequest::setVar('id', 0);
            $start = new DateTime(JRequest::getVar('start_date'));
            $end = new DateTime(JRequest::getVar('end_date'));
            $until = new DateTime(JRequest::getVar('repeat_until'));
            while ($until > $start) {
                switch ($repeat) {
                    case "day": {
                            $start->modify("+1 days");
                            $end->modify("+1 days");
                            break;
                        }
                    case "week": {
                            $start->modify("+7 days");
                            $end->modify("+7 days");
                            break;
                        }
                    case "2week": {
                            $start->modify("+14 days");
                            $end->modify("+14 days");
                            break;
                        }
                    case "month": {
                            $start->modify("+1 months");
                            $end->modify("+1 months");
                            break;
                        }
                    case "year": {
                            $start->modify("+1 years");
                            $end->modify("+1 years");
                            break;
                        }
                }
                JRequest::setVar('start_date', $start->format('Y-m-d'));
                JRequest::setVar('end_date', $end->format('Y-m-d'));
//                        echo $start->format('Y-m-d').'-'.$end->format('Y-m-d');
                if ($until >= $start) {
//                    $return = $this->store();
//                    if ($return == 0)
//                        $i++;
                }
            }
            if ($i != 0) {
                $id_room = JRequest::getVar('id_room');
                $msg = JText::_('SERIESSAVED') . ': ' . $i . ' ' . JText::_('BOOKSNOSAVED');
                $type = 'notice';
                $link = 'index.php?option=com_roombooking&view=bookinglist&id_room=' . $id_room;
                $this->setRedirect($link, $msg, $type);
            }
        }
    }

    /**
     * save a record and redirect
     * @return void
     */
    function store() {
        $id_booking = JRequest::getVar('id');
        $params = &JComponentHelper::getParams('com_roombooking');
        $edit_gid = $params->get('edit_group');
        $model = &$this->getModel('booking');
        $id_user = $model->getUserID($id_booking);
        $userID_logg = JFactory::getUser()->id;
        $user_gid = JFactory::getUser()->gid;

        if (( ($id_user == $userID_logg || $user_gid > $edit_gid) && $id_booking != 0) || ($id_booking == 0 && $userID_logg > 0)) {

            JRequest::setVar('start', JRequest::getVar('start_date') . ' ' . JRequest::getVar('start_hour') . ':' . JRequest::getVar('start_minute'));
            JRequest::setVar('end', JRequest::getVar('end_date') . ' ' . JRequest::getVar('end_hour') . ':' . JRequest::getVar('end_minute'));
            $booking = JRequest::get('POST');
            if ($booking['short_description'] && $booking['start'] && $booking['end'] && $booking['id_room'] && $booking['id_user']) {
                $start = $booking['start'];
                $end = $booking['end'];
                $id_room = $booking['id_room'];
                $available = $this->roomAvailable($start, $end, $id_room, $id_booking);
                if ($available == 1) {
                    if ($returnid = $model->store($post)) {
                        $msg = JText::_('BOOKSAVED');
                        $type = 'message';
                        $link = 'index.php?option=com_roombooking&view=bookings&id_room=' . $booking['id_room'];
                        $addresses = $params->get('mail_notify');
                        $addresses = explode(',', $addresses);
                        foreach ($addresses as $address)
                            if (JMailHelper::isEmailAddress($address))
                                if (!$booking['id'] > $booking['series'])
                                    $this->notifyMail($address, 'index.php?option=com_roombooking&controller=booking&cid=' . $returnid);
                    } else {
                        $msg = JText::_('SAVEBOOKERROR');
                        $type = 'error';
                    }
                } else {
                    if ($available == 0)
                        $msg = JText::_('ROOMBUSY');
                    else if ($available == -1)
                        $msg = JText::_('NOCLOSINGTIME');
                    $type = 'error';
                    $return = $available;
                }
            }
            else {
                $msg = JText::_('FIELDMISSING');
                $type = 'error';
            }
            $link = 'index.php?option=com_roombooking&view=bookinglist&id_room=' . $id_room;
            $this->setRedirect($link, $msg, $type);
            return $returnid;
        }
        else
            JFactory::getApplication()->enqueueMessage(JText::_('NOAUTH'), 'notice');
    }

    /**
     * remove record(s)
     * @return void
     */
    function remove() {
        $id_booking = JRequest::getVar('id');
        $cids = JRequest::getVar( 'cid', array(0), 'post', 'array' );

        //check user privileges
        $params = &JComponentHelper::getParams('com_roombooking');
        $edit_gid = $params->get('edit_group');
//        $id_user = $this->getModel('booking')->getUserID($id_booking);
        $userID_logg = JFactory::getUser()->id;
        $user_gid = JFactory::getUser()->gid;
        if (/*($id_user == $userID_logg || $user_gid > $edit_gid) && */$id_booking != 0 || $cids != 0) {

            $id_room = JRequest::getVar('id_room');
            $model = $this->getModel('booking');
            if (!$model->delete()) {
                $msg = JText::_('NOBOOKINGDELETE');
                $link = 'index.php?option=com_roombooking&view=booking&layout=form&cid=' . $id_booking;
                $type = 'error';
            } else {
                $msg = JText::_('BOOKDELETE');
                $link = 'index.php?option=com_roombooking&view=bookinglist&id_room=' . $id_room;
                $type = 'message';
            }
            $this->setRedirect($link, $msg, $type);
        }
        else
            JFactory::getApplication()->enqueueMessage(JText::_('NOAUTH'), 'notice');
    }

    /**
     * remove series
     * @return void
     */
    function removeSeries() {
        $series = JRequest::getVar('series');
        $id_booking = JRequest::getVar('id');
        $id_room = JRequest::getVar('id_room');

        //check user privileges
        $params = &JComponentHelper::getParams('com_roombooking');
        $edit_gid = $params->get('edit_group');
        $id_user = $this->getModel('booking')->getUserID($id_booking);
        $userID_logg = JFactory::getUser()->id;
        $user_gid = JFactory::getUser()->gid;
        if (($id_user == $userID_logg || $user_gid > $edit_gid) && $id_booking != 0) {
            $model = $this->getModel('booking');
            if (!$model->deleteSeries($series)) {
                $msg = JText::_('NOSERIESINGDELETE');
                $link = 'index.php?option=com_roombooking&view=booking&layout=form&cid=' . $id_booking;
                $type = 'error';
            } else {
                $msg = JText::_('SERIESDELETE');
                $link = 'index.php?option=com_roombooking&view=bookings&id_room=' . $id_room;
                $type = 'message';
            }
            $this->setRedirect($link, $msg, $type);
        }
        else
            JFactory::getApplication()->enqueueMessage(JText::_('NOAUTH'), 'notice');
    }

    /**
     * cancel editing a record
     * @return void
     */
    function cancel() {
        $id_room = JRequest::getVar('id_room');
        $this->setRedirect('index.php?option=com_roombooking&view=bookings&id_room=' . $id_room);
    }

    /**
     * verify the room availability
     * @return mixed
     */
    function roomAvailable($start, $end, $id_room, $id_booking) {
        JLoader::import('room', JPATH_COMPONENT_SITE . DS . 'models');
        $modelRoom = & JModel::getInstance('room', 'RoomBookingModel');
        $id_building = $modelRoom->getIdBuildOfRoom($id_room);
        JLoader::import('building', JPATH_COMPONENT_SITE . DS . 'models');
        $modelBuilding = & JModel::getInstance('building', 'RoomBookingModel');

        $opening = new DateTime($start);
        $closing = new DateTime($end);
        $start = new DateTime($start);
        $end = new DateTime($end);
        $today = new DateTime('now');

        if ($start >= $today)
            $we_opening = $modelBuilding->getWEOpening($id_building);
        else
            return JText::_('NOBOOKINPAST');
        if ($we_opening == 0 && ($end->format('N') == 6 || $end->format('N') == 7 || $start->format('N') == 6 || $start->format('N') == 7))
            return JText::_('NOSUNSAT');
        $times = $modelBuilding->getBuildOpenCloseTime($id_building);

        $times->opening = explode(':', $times->opening);
        $opening->setTime($times->opening[0], $times->opening[1]);
        $times->closing = explode(':', $times->closing);
        $closing->setTime($times->closing[0], $times->closing[1]);
//        var_dump($start);
//$this->roomLog($start.getdate());
        if ($start >= $opening && $end <= $closing) {
            $modelBookings = & $this->getModel('bookings');
            $bookings = & $modelBookings->getRoomBookings($id_room, $id_booking);

            foreach ($bookings as $booking) {
                $start_booking = new DateTime($booking->start);
                $end_booking = new DateTime($booking->end);
                if (($start >= $start_booking && $start < $end_booking) ||
                        ($start < $start_booking && $end > $start_booking))
                    return 0;
            }
            return 1;
        }
        else
            return -1;
    }
    
    function roomLog($comment) {
        jimport('joomla.error.log');
        // Define the file name as a PHP constant
        define('ROOM_LOG', 'room.log.' . date('Y_m_d') . '.php');

        $log = &JLog::getInstance(ROOM_LOG);

        // Just adding a comment
        $log->addEntry(array('comment' => $comment));
    }

    /**
     * Sends mail notify of new add/edit booking
     * @return void
     */
    function notifyMail($address, $link) {

        $mailer = & JFactory::getMailer();
        $config = & JFactory::getConfig();
        $sender = array(
            $config->getValue('config.mailfrom'),
            $config->getValue('config.fromname'));

        $mailer->setSender($sender);
        $mailer->addRecipient($address);

        $booking = JRequest::get('POST');
        $modelRoom = $this->getModel('room');
        $room = $modelRoom->getRoomName($booking['id_room']);
        $id_building = $modelRoom->getIdBuildOfRoom($booking['id_room']);
        $modelBuildings = $this->getModel('building');
        $building = $modelBuildings->getBuildName($id_building);

        if (JRequest::getVar('id') == 0) {
            $body = JText::_('NEWBODYMAIL') . ':<br /><br />';
            $mailer->setSubject(JText::_('NEWSUBMAIL'));
        } else {
            $body = JText::_('EDITBODYMAIL') . ':<br /><br />';
            $mailer->setSubject(JText::_('EDITSUBMAIL'));
        }
        $body.=JText::_('Room') . ': ' . $room . ' - ' . $building . '<br />' .
                JText::_('SHORTDESC') . ': ' . $booking['short_description'] . ' <br />' .
                JText::_('DESC') . ': ' . $booking['description'] . ' <br />' .
                JText::_('STARTDATE') . ': ' . $booking['start'] . ' <br />' .
                JText::_('ENDDATE') . ': ' . $booking['end'] . ' <br />' .
                JText::_('REPEAT') . ': ';
        switch ($booking['repeat_type']) {
            case "0": {
                    $body.= JText::_('NEVER');
                    break;
                }
            case "day": {
                    $body.= JText::_('EVERYDAY');
                    break;
                }
            case "week": {
                    $body.= JText::_('EVERYWEEK');
                    break;
                }
            case "2week": {
                    $body.= JText::_('EVERY2WEEK');
                    break;
                }
            case "month": {
                    $body.= JText::_('EVERYMONTH');
                    break;
                }
            case "year": {
                    $body.= JText::_('EVERYYEAR');
                    break;
                }
        }
        $body.='<br />' . JText::_('UNTIL') . ': ' . $booking['repeat_until'] . ' <br />' .
                JText::_('NOTES') . ': ' . $booking['notes'] . ' <br />' .
                JText::_('USER') . ': ' . JFactory::getUser()->name . ' <br /><br />
				<a href="' . JURI::base() . $link . '">' . JText::_('MOREINFO') . '</a>';
        $mailer->isHTML(true);
        $mailer->setBody($body);
        $mailer->Send();
    }

}
